package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Name CategoryController
 * @Author stella
 * @Date 2023-03-08 2:50 PM
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取分类列表
     * @return
     */
    @GetMapping("/list")
    public ResultInfo getList(){
        // 先查缓存有没有
        List<Category> list= null;
        String categoryKey = "category_list";
        if (redisTemplate.hasKey(categoryKey)){
             list = (List<Category> ) redisTemplate.opsForValue().get(categoryKey);
             log.info("查询redis缓存");
        }else{
            list = categoryService.findAll();
            log.info("查询数据库mysql");
            // 同步到redis
            redisTemplate.opsForValue().set(categoryKey,list);
        }
        return ResultInfo.success(list);
    }


}
